package com.zgkxzx.java.mutilThread.PCModel;

import android.util.Log;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 创建者 zgkxzx
 * 日期   12/29/17
 * 描述
 */

public class EventLockModel extends Model {
    private final static String TAG = EventLockModel.class.getSimpleName();

    private List<Date> events;
    private int max = 10;

    private Lock lock;
    private Condition condition;


    public EventLockModel() {
        events = new LinkedList<>(); 
        lock = new ReentrantLock();
        condition = lock.newCondition();
    }

    @Override
    public void putEvent() {
        lock.lock();
        while (events.size() == max) {
            try {
                //wait();
                condition.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        Date date = new Date();
        events.add(date);
        Log.d(TAG, "添加一个事件 " + date);
        condition.signal();
        lock.unlock();
    }

    @Override
    public void getEvent() {
        lock.lock();
        while (events.size() == 0) {
            try {
                condition.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        Date poll = (Date) ((LinkedList) events).poll();
        Log.d(TAG, "push 一个事件" + poll + " 还有ge " + events.size());
        condition.signal();

        lock.unlock();

    }


}
